#pragma once
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <unordered_map>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <regex>
#include "Server.hpp"
#define DEFAULT_TIMEOUT 10
#define INF 0
#define DBG 1
#define ERR 2
#define LOG_LEVEL INF
#define LOG(level, format, ...)                                                                                        \
    do                                                                                                                 \
    {                                                                                                                  \
        if (level < INF)                                                                                               \
            break;                                                                                                     \
        time_t t = time(NULL);                                                                                         \
        struct tm *ltm = localtime(&t);                                                                                \
        char tmp[32] = {0};                                                                                            \
        strftime(tmp, 31, "%H:%M:%S", ltm);                                                                            \
        fprintf(stdout, "[%p %s %s:%d] " format "\n", (void *)pthread_self(), tmp, __FILE__, __LINE__, ##__VA_ARGS__); \
    } while (0)
#define INF_LOG(format, ...) LOG(INF, format, ##__VA_ARGS__)
#define DBG_LOG(format, ...) LOG(DBG, format, ##__VA_ARGS__)
#define ERR_LOG(format, ...) LOG(ERR, format, ##__VA_ARGS__)
using namespace std;
unordered_map<int, string> _statu_msg = {
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}};

unordered_map<string, string> _mime_msg = {
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformatsofficedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformatsofficedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}};
class Util
{
public:
    static size_t
    // 分割字符串 将 src 按照 sep 分割后放入 arry
    Split(const string &src, const string &sep, vector<string> &arry)
    {
        int offset = 0;
        while (offset < src.size())
        {
            auto pos = src.find(sep, offset);
            if (pos == string::npos)
            {
                arry.push_back(src.substr(offset));
                return arry.size();
            }
            else
            {
                if (pos == offset)
                {
                    ++offset;
                    continue;
                }
                arry.push_back(src.substr(offset, pos - offset));
            }
            offset = pos + sep.size();
        }
        return arry.size();
    }
    // 读取文件
    static bool ReadFile(const string &filename, string &buffer)
    {
        ifstream ifs(filename, ios::binary);
        if (ifs.is_open() == false)
        {
            DBG_LOG("Open file failed");
            ifs.close();
            return false;
        }
        ifs.seekg(0, ifs.end);
        size_t size = ifs.tellg();
        buffer.resize(size);
        ifs.seekg(0, ifs.beg);
        ifs.read(&(buffer[0]), size);
        if (ifs.good() == false)
        {
            DBG_LOG("Read file failed");
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
    }
    // 写入文件
    static bool WriteFile(const string &filename, const string &buffer)
    {
        ofstream ofs(filename, ios::binary | ios::trunc);
        if (ofs.is_open() == false)
        {
            DBG_LOG("Open file failed");
            ofs.close();
            return false;
        }
        ofs.write(buffer.c_str(), buffer.size());
        if (ofs.good() == false)
        {
            DBG_LOG("Read file failed");
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }
    // URL加码
    static string UrlEncode(const string &url, bool flag = false)
    {
        string ret;
        ret.resize(url.size());
        for (auto &ch : url)
        {
            if (ch == '.' || ch == '-' || ch == '~' || ch == '_' || isalnum(ch))
                ret += ch;
            else if (ch == ' ' && flag)
                ret += '+';
            else
            {
                char tmp[4];
                snprintf(tmp, 4, "%%%02X", ch);
                ret += tmp;
            }
        }
        return ret;
    }
    // 将字符转换为十六进制
    static char HEXTOI(char c)
    {
        if ('0' <= c && c <= '9')
            return c - '0';
        else if ('a' <= c && c <= 'z')
            return c - 'a' + 10;
        else if ('A' <= c && c <= 'Z')
            return c - 'A' + 10;
        return -1;
    }
    // Url 解码
    static string UrlDecode(const string &url, bool flag = false)
    {
        std::string res;
        for (int i = 0; i < url.size(); i++)
        {
            if (url[i] == '+' && flag == true)
            {
                res += ' ';
                continue;
            }
            if (url[i] == '%' && (i + 2) < url.size())
            {
                char v1 = HEXTOI(url[i + 1]);
                char v2 = HEXTOI(url[i + 2]);
                char v = v1 * 16 + v2;
                res += v;
                i += 2;
                continue;
            }
            res += url[i];
        }
        return res;
    }
    // 根据状态码获取状态信息
    static string StatuDesc(int statu)
    {
        auto it = _statu_msg.find(statu);
        if (it != _statu_msg.end())
        {
            return it->second;
        }
        return "Unknow";
    }
    // 根据文件后缀获取文件类型信息
    static string ExtMime(const string &filename)
    {
        size_t pos = filename.find_last_of('.');
        if (pos == std::string::npos)
        {
            return "application/octet-stream";
        }
        std::string ext = filename.substr(pos);
        auto it = _mime_msg.find(ext);
        if (it == _mime_msg.end())
        {
            return "application/octet-stream";
        }
        return it->second;
    }
    // 判断文件路径是否为目录
    static bool IsDirectory(const string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;
        return S_ISDIR(st.st_mode);
    }
    // 判断文件路径是否为普通文件
    static bool IsRegular(const string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISREG(st.st_mode);
    }
    // 判断路径是否为有效路径
    static bool VaildPath(const string &path)
    {
        vector<string> arry;
        Split(path, "/", arry);
        int count = 0;
        for (auto &s : arry)
        {
            if (s == "..")
            {
                --count;
                if (count < 0)
                    return false;
            }
            else
                ++count;
        }
        return true;
    }
};

class HttpRequest
{
public:
    string _method;
    string _path;
    string _version;
    string _body;
    smatch _matches;
    unordered_map<string, string> _headers;
    unordered_map<string, string> _params;

public:
    // 重置 Request 对象
    void ReSet()
    {
        _method.clear();
        _path.clear();
        _version.clear();
        _body.clear();
        smatch matches;
        _matches.swap(matches);
        _headers.clear();
        _params.clear();
    }
    // 设置请求头部信息
    void SetHeader(const string &key, const string &val)
    {
        _headers.insert(make_pair(key, val));
    }
    // 是否存在请求头部信息
    bool HasHeader(const string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return false;
        return true;
    }
    // 获取请求头部 val 值
    string GetHeader(const string &key)
    {
        if (HasHeader(key) == false)
            return "";
        return _headers[key];
    }
    // 设置请求行资源路径信息 password=123
    void SetParam(const string &key, const string &val)
    {
        _params.insert(make_pair(key, val));
    }
    // 请求行是否存在资源路径信息
    bool HasParam(const string &key)
    {
        auto it = _params.find(key);
        if (it == _params.end())
            return false;
        return true;
    }
    // 获取请求行资源路径 val 值
    string GetParam(const string &key)
    {
        if (HasParam(key) == false)
            return "";
        return _params[key];
    }
    // 获取请求正文长度
    size_t ContentLength()
    {
        bool ret = HasHeader("Content-Length");
        if (ret == false)
            return 0;
        string s = _headers["Content-Length"];
        return stol(s);
    }
    // 判断是否为短链接
    bool Close()
    {
        if (HasHeader("Connection") && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};
class HttpResponse
{
public:
    int _statu;
    bool _redirect_flag;
    string _body;
    string _redirect_url;
    unordered_map<string, string> _headers;

public:
    HttpResponse() : _redirect_flag(false), _statu(200) {}
    HttpResponse(int statu) : _redirect_flag(false), _statu(statu) {}
    // 重置 Response 对象
    void ReSet()
    {
        _statu = 200;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }
    // 设置响应头部信息
    void SetHeader(const string &key, const string &val)
    {
        _headers.insert(make_pair(key, val));
    }
    // 是否存在响应头部信息
    bool HasHeader(const string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return false;
        return true;
    }
    // 获取响应头部信息 val 值
    string GetHeader(const string &key)
    {
        if (HasHeader(key) == false)
            return "";
        return _headers[key];
    }
    // 设置响应报文正文
    void SetContent(const string &body, const string &type)
    {
        _body = body;
        SetHeader("Content-Type", type);
    }
    // 设置重定向
    void SetRedirect(const string &url, int statu = 302)
    {
        _statu = statu;
        _redirect_flag = true;
        _redirect_url = url;
    }
    // 判断是否为短链接
    bool Close()
    {
        if (HasHeader("Connection") && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};
#define MAX_LINE 8192
enum HttpRecvStatu
{
    HTTP_RECV_ERROR,
    HTTP_RECV_LINE,
    HTTP_RECV_HEAD,
    HTTP_RECV_BODY,
    HTTP_RECV_OVER
};
class HttpContext
{
private:
    int _resp_statu;           // 响应状态码
    HttpRecvStatu _recv_statu; // 当前接收及解析的阶段信息
    HttpRequest _request;      // 已经解析得到的请求内容

private:
    // 分析 Http 请求行信息
    bool ParseHttpLine(string &line)
    {
        smatch matches;
        regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", regex::icase);
        bool ret = regex_match(line, matches, e);
        if (ret == false)
        {
            _resp_statu = 400;
            _recv_statu = HTTP_RECV_ERROR;
            return false;
        }
        _request._method = matches[1];
        transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        _request._path = Util::UrlDecode(matches[2], false);
        _request._version = matches[4];
        string str = matches[3];
        vector<string> arry;
        Util::Split(str, "&", arry);
        for (auto &s : arry)
        {
            size_t pos = str.find("=");
            if (pos == string::npos)
            {
                _resp_statu = 400;
                _recv_statu = HTTP_RECV_ERROR;
                return false;
            }
            string key = Util::UrlDecode(s.substr(0, pos), true);
            string val = Util::UrlDecode(s.substr(pos + 1), true);
            _request.SetParam(key, val);
        }
        return true;
    }
    // 读取 Http 请求行信息
    bool RecvHttpLine(Buffer &buffer)
    {
        if (_recv_statu != HTTP_RECV_LINE)
            return false;
        string str = buffer.GetLine();
        if (str.size() == 0)
        {
            if (buffer.getReadSpace() >= MAX_LINE)
            {
                _resp_statu = 413;
                _recv_statu = HTTP_RECV_ERROR;
                return false;
            }
        }
        if (str.size() >= MAX_LINE)
        {
            _resp_statu = 413;
            _recv_statu = HTTP_RECV_ERROR;
            return false;
        }
        bool ret = ParseHttpLine(str);
        if (ret == false)
            return false;
        _recv_statu = HTTP_RECV_HEAD;
        return true;
    }
    // 分析 Http 头部信息
    bool ParseHttpHead(string &line)
    {
        if (line.back() == '\n')
            line.pop_back();
        if (line.back() == '\r')
            line.pop_back();
        size_t pos = line.find(": ");
        if (pos == string::npos)
        {
            _resp_statu = 400;
            _recv_statu = HTTP_RECV_ERROR;
            return false;
        }
        string key = Util::UrlDecode(line.substr(0, pos), true);
        string val = Util::UrlDecode(line.substr(pos + 2), true);
        _request.SetHeader(key, val);
        return true;
    }
    // 读取 Http 头部信息
    bool RecvHttpHead(Buffer &buffer)
    {
        if (_recv_statu != HTTP_RECV_HEAD)
            return false;
        while (1)
        {
            string str = buffer.GetLine();
            if (str.size() == 0)
            {
                if (buffer.getReadSpace() >= MAX_LINE)
                {
                    DBG_LOG("str.size() == 0");
                    _resp_statu = 413;
                    _recv_statu = HTTP_RECV_ERROR;
                    return false;
                }
            }
            if (str.size() >= MAX_LINE)
            {
                DBG_LOG("str.size() >= MAX_LINE");
                _resp_statu = 413;
                _recv_statu = HTTP_RECV_ERROR;
                return false;
            }
            if (str == "\n" || str == "\r\n")
                break;

            bool ret = ParseHttpHead(str);
            if (ret == false)
            {
                DBG_LOG("bool ret = ParseHttpHead(str)");
                return false;
            }
        }
        _recv_statu = HTTP_RECV_BODY;
        return true;
    }
    // 读取 Http 报文正文
    bool RecvHttpBody(Buffer &buffer)
    {
        if (_recv_statu != HTTP_RECV_BODY)
            return false;
        size_t total_len = _request.ContentLength();
        if (total_len == 0)
        {
            _recv_statu = HTTP_RECV_OVER;
            return true;
        }
        size_t real_len = total_len - _request._body.size();
        if (buffer.getReadSpace() < real_len)
        {
            _request._body.append(buffer.getReadAddr(), buffer.getReadSpace());
            buffer.moveReadPosition(buffer.getReadSpace());
            return true;
        }
        _request._body.append(buffer.getReadAddr(), real_len);
        buffer.moveReadPosition(real_len);
        _recv_statu = HTTP_RECV_OVER;
        return true;
    }

public:
    HttpContext() : _resp_statu(200), _recv_statu(HTTP_RECV_LINE) {}
    void Reset()
    {
        _resp_statu = 200;
        _recv_statu = HTTP_RECV_LINE;
        _request.ReSet();
    }
    // 获取响应状态码
    int RespStatu()
    {
        return _resp_statu;
    }
    // 获取Http处理状态
    HttpRecvStatu RecvStatu()
    {
        return _recv_statu;
    }
    // 获取Http请求报文
    HttpRequest &Request()
    {
        return _request;
    }
    // 处理 Http 报文
    void RecvHttpRequest(Buffer &buffer)
    {
        switch (_recv_statu)
        {
        case HTTP_RECV_LINE:
            RecvHttpLine(buffer);
            break;
        case HTTP_RECV_HEAD:
            RecvHttpHead(buffer);
            break;
        case HTTP_RECV_BODY:
            RecvHttpBody(buffer);
            break;
        default:
            break;
        }
    }
};

class HttpServer
{
private:
    using Handler = function<void(const HttpRequest &, HttpResponse &)>;
    using Handlers = vector<pair<regex, Handler>>;
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    string _basedir;
    TcpServer _server;

private:
    // 处理错误请求并回送错误请求页面
    void ErrorHandler(const HttpRequest &req, HttpResponse &rsp)
    {
        string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content = 'text/html;charset=utf-8' > ";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(rsp._statu);
        body += " ";
        body += Util::StatuDesc(rsp._statu);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        rsp.SetContent(body, "text/html");
        rsp._body = body;
    }
    // 发送业务处理
    void WriteResponse(const ConnectionPtr &conn, HttpRequest &req, HttpResponse &rsp)
    {
        if (req.Close() == true)
            rsp.SetHeader("Connection", "close");
        else
            rsp.SetHeader("Connection", "keep-alive");
        if (rsp._body.empty() == false && rsp.HasHeader("Content-Length") == false)
            rsp.SetHeader("Content-Length", to_string(rsp._body.size()));
        if (rsp._body.empty() == false && rsp.HasHeader("Content-Type") == false)
            rsp.SetHeader("Content-Type", "application/octet-stream");
        if (rsp._redirect_flag == true)
            rsp.SetHeader("Location", rsp._redirect_url);
        stringstream rsp_str;
        rsp_str << req._version << " " << to_string(rsp._statu) << " " << Util::StatuDesc(rsp._statu) << "\r\n";
        for (auto &it : rsp._headers)
            rsp_str << it.first << ": " << it.second << "\r\n";
        rsp_str << "\r\n";
        rsp_str << rsp._body;
        conn->Send(rsp_str.str().c_str(), rsp_str.str().size());
    }
    // 判断请求是否为静态资源
    bool IsFileHandler(const HttpRequest &req)
    {
        if (_basedir.empty())
            return false;
        if (req._method != "GET" && req._method != "POST")
            return false;
        if (Util::VaildPath(req._path) == false)
            return false;
        string path = _basedir + req._path;
        if (path.back() == '/')
            path += "index.html";
        if (Util::IsRegular(path) == false)
            return false;
        return true;
    }
    // 静态资源请求业务处理
    void FileHandler(const HttpRequest &req, HttpResponse &rsp)
    {
        string path = _basedir + req._path;
        if (path.back() == '/')
            path += "index.html";
        bool ret = Util::ReadFile(path, rsp._body);
        if (ret == false)
        {
            return;
        }
        string mime = Util::ExtMime(path);
        rsp.SetHeader("Content-Type", mime);
    }
    // 动态资源请求业务处理
    void Dispatcher(HttpRequest &req, HttpResponse &rsp, Handlers &handlers)
    {
        for (auto &handler : handlers)
        {
            regex &e = handler.first;
            Handler &functor = handler.second;
            bool ret = regex_match(req._path, req._matches, e);
            if (ret == false)
            {
                continue;
            }
            return functor(req, rsp);
        }
        rsp._statu = 404;
    }
    // 根据请求进行路由
    void Route(HttpRequest &req, HttpResponse &rsp)
    {
        if (IsFileHandler(req) == true)
            FileHandler(req, rsp);
        if (req._method == "GET" || req._method == "HEAD")
        {
            return Dispatcher(req, rsp, _get_route);
        }
        else if (req._method == "POST")
        {
            return Dispatcher(req, rsp, _post_route);
        }
        else if (req._method == "PUT")
        {
            return Dispatcher(req, rsp, _put_route);
        }
        else if (req._method == "DELETE")
        {
            return Dispatcher(req, rsp, _delete_route);
        }
        else
        {
            rsp._statu = 405;
        }
    }
    // 建立连接时的业务处理
    void OnConnected(const ConnectionPtr &conn)
    {
        DBG_LOG("Get new connection : %p", conn->get());
        conn->SetContext(HttpContext());
    }
    // 接收数据后的业务处理
    void OnMessage(const ConnectionPtr &conn, Buffer &buffer)
    {
        while (buffer.getReadSpace() > 0)
        {
            HttpContext &context = conn->GetContext()->getVal<HttpContext>();
            context.RecvHttpRequest(buffer);
            HttpRequest &req = context.Request();
            HttpResponse rsp(context.RespStatu());
            if (context.RespStatu() > 400)
            {
                ErrorHandler(req, rsp);
                WriteResponse(conn, req, rsp);
                context.Reset();
                buffer.moveReadPosition(buffer.getReadSpace());
                conn->Shutdown();
                return;
            }
            if (context.RecvStatu() != HTTP_RECV_OVER)
            {
                return;
            }
            Route(req, rsp);
            WriteResponse(conn, req, rsp);
            context.Reset();
            if (rsp.Close() == true)
            {
                conn->Shutdown();
                return;
            }
        }
    }

public:
    HttpServer(int port, int timeout = DEFAULT_TIMEOUT) : _server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(bind(&HttpServer::OnConnected, this, placeholders::_1));
        _server.SetMessageCallback(bind(&HttpServer::OnMessage, this, placeholders::_1, placeholders::_2));
    }
    // 设置静态资源根目录
    void SetBaseDir(const string &path)
    {
        assert(Util::IsDirectory(path) == true);
        _basedir = path;
    }
    // 设置GET请求方法对应路由
    void Get(const string &pattern, const Handler &handler)
    {
        _get_route.push_back(make_pair(regex(pattern), handler));
    }
    // 设置POST请求方法对于路由
    void Post(const string &pattern, const Handler &handler)
    {
        _post_route.push_back(make_pair(regex(pattern), handler));
    }
    // 设置PUT请求方法对应路由
    void Put(const string &pattern, const Handler &handler)
    {
        _put_route.push_back(make_pair(regex(pattern), handler));
    }
    // 设置DELETE请求方法对应路由
    void Delete(const string &pattern, const Handler &handler)
    {
        _delete_route.push_back(make_pair(regex(pattern), handler));
    }
    // 设置从属Epoll个数
    void SetThreadCount(int count)
    {
        _server.SetThreadCount(count);
    }
    // 开始监听
    void Listen()
    {
        _server.Start();
    }
};